/*
 * Copyright (c) 2014 jbing.org
 */
package jbing.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

/**
 * jbing.log.LogHPropSupport (Log Have Properties)
 * 
 * @author 旧城(jbing.org@gmail.com)
 * @date 2014/03/19
 * @version 0.0.2
 */
public class LogHPropSupport extends AbstractLog {

	private LogHPropSupport() {
	}

	public void debug(String debug) {
		go(isDebug, "DEBUG", debug);
	}

	public void warn(String warn) {
		go(isWarn, "WARN", warn);
	}

	public void error(String error) {
		go(isError, "ERROR", error);
	}

	public void info(String info) {
		go(isInfo, "INFO", info);
	}

	public void fatal(String fatal) {
		go(isFatal, "FATAL", fatal);
	}
	
	@SuppressWarnings("deprecation")
	private void go(boolean is, String tipTitle, String tip) {
		if (is) {
			StackTraceElement[] stes = Thread.currentThread().getStackTrace();
			String out = String.format(this.format, tip,
					this.clazz.getName(), stes[stes.length - 1],
					new Date().toLocaleString());
			for (StackTraceElement ste : stes) {
				if (ste.getClassName().equals(clazz.getName())) {
					out = String.format(this.format, tip,
							this.clazz.getName(), ste.getLineNumber(),
							new Date().toLocaleString());
					break;
				}
			}
			if (isFile) {
				PrintWriter bw = null;
				try {
					File file = new File(filePath);
					bw = new PrintWriter(new OutputStreamWriter(
							new FileOutputStream(file, true), "UTF-8"));
					bw.println(tipTitle+":"+out);
				} catch (Exception e) {

				} finally {
					if (bw != null) {
						bw.close();
					}
				}
			}
			if (isConsole) {
				synchronized (out) {
					System.out.println(tipTitle+":"+out);
				}
			}
		}
	}
}
